package com.zzedu.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zzedu.common.enums.CommonEnums;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.common.utils.bean.BeanUtils;
import com.zzedu.common.utils.file.FileUtils;
import com.zzedu.common.utils.uuid.IdUtils;
import com.zzedu.domain.ZzCourse;
import com.zzedu.domain.ZzPictureBook;
import com.zzedu.domain.ZzPictureNode;
import com.zzedu.domain.ZzUploadFile;
import com.zzedu.dto.QueryZzPictureBookDTO;
import com.zzedu.dto.ZzPictureBookDTO;
import com.zzedu.enmuns.FileRelationTypeEnum;
import com.zzedu.integration.oss.IOssClientService;
import com.zzedu.integration.oss.dto.FileInfoDTO;
import com.zzedu.integration.oss.dto.OssFileResult;
import com.zzedu.mapper.ZzPictureBookMapper;
import com.zzedu.params.ZzPictureBookParams;
import com.zzedu.params.ZzUploadFileParams;
import com.zzedu.service.IZzCourseService;
import com.zzedu.service.IZzPictureBookService;
import com.zzedu.service.IZzPictureNodeService;
import com.zzedu.service.IZzUploadFileService;
import com.zzedu.system.service.ISysConfigService;
import com.zzedu.vo.ZzPictureBookVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 课程管理Service业务层处理
 *
 * @author Mr.Wang
 * @date 2025-04-04
 */
@Service
public class ZzPictureBookServiceImpl extends ServiceImpl<ZzPictureBookMapper, ZzPictureBook> implements IZzPictureBookService {


    @Autowired
    IZzUploadFileService zzUploadFileService;

    @Autowired
    IOssClientService ossClientService;

    @Autowired
    ISysConfigService sysConfigService;

    @Autowired
    IZzCourseService zzCourseService;

    @Autowired
    IZzPictureNodeService zzPictureNodeService;

    @Override
    public LambdaQueryWrapper<ZzPictureBook> buildQuery(ZzPictureBookDTO zzContentHead) {
        LambdaQueryWrapper<ZzPictureBook> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(zzContentHead.getName()), ZzPictureBook::getName, zzContentHead.getName());
        lambdaQueryWrapper.eq(null != zzContentHead.getState(), ZzPictureBook::getState, zzContentHead.getState());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(zzContentHead.getLevel()), ZzPictureBook::getLevel, zzContentHead.getLevel());
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(zzContentHead.getUnitIdArray()), ZzPictureBook::getUnitId, zzContentHead.getUnitIdArray());
        lambdaQueryWrapper.orderByAsc(ZzPictureBook::getSortNo).orderByDesc(ZzPictureBook::getId);
        return lambdaQueryWrapper;
    }

    @Override
    public List<ZzPictureBookVO> convertVO(List<ZzPictureBook> zzPictureBooks) {

        return Optional.ofNullable(zzPictureBooks).orElse(Lists.newArrayList()).stream().map(zzPictureBook -> {
            ZzPictureBookVO zzPictureBookVO = new ZzPictureBookVO();
            BeanUtils.copyBeanProp(zzPictureBookVO, zzPictureBook);
            if (StringUtils.isNotBlank(zzPictureBook.getTag())) {
                zzPictureBookVO.setTag(JSON.parseArray(zzPictureBook.getTag(), String.class));
            }
            if (null != zzPictureBook.getUnitId()) {
                ZzCourse zzCourse = this.zzCourseService.getById(zzPictureBook.getUnitId());
                if (null != zzCourse) {
                    zzPictureBookVO.setUnitName(zzCourse.getName());
                }
            }
            return zzPictureBookVO;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class, readOnly = false)
    public boolean save(ZzPictureBookParams zzPictureBookParams) throws Exception {
        ZzPictureBook zzPictureBook = new ZzPictureBook();
        BeanUtils.copyBeanProp(zzPictureBook, zzPictureBookParams);
        zzPictureBook.setState(CommonEnums.NO.getCode());
        if(null!=zzPictureBook.getId()){
            zzPictureBook.setState(null);
        }
        //封面处理
        List<ZzUploadFileParams> uploadFileParamsList = zzPictureBookParams.getCoverArray();
        List<Long> coverIdList = Lists.newArrayList();
        List<Long> videoIdList = Lists.newArrayList();
        FileRelationTypeEnum fileRelationTypeEnum = FileRelationTypeEnum.PICTURE_BOOK;
        if (CollectionUtils.isNotEmpty(uploadFileParamsList)) {
            for (ZzUploadFileParams fileParams : uploadFileParamsList) {
                if (fileParams.getFile() != null) {
                    OssFileResult<FileInfoDTO> fileUploadResult = ossClientService.uploadFile(fileParams.getFile().getBytes(), fileRelationTypeEnum.getOssPath(), fileParams.getFile().getOriginalFilename(), IdUtils.fastSimpleUUID());
                    if (fileUploadResult.isSuccess()) {
                        FileInfoDTO fileInfoDTO = fileUploadResult.getData();
                        ZzUploadFile uploadFile = new ZzUploadFile();
                        uploadFile.setRelationType(fileRelationTypeEnum.getCode());
                        uploadFile.setUrl(fileInfoDTO.getUrl());
                        uploadFile.setOldFileName(fileInfoDTO.getOriginalFilename());
                        uploadFile.setFileName(FileUtils.getName(fileInfoDTO.getNewFileName()));
                        if (null != zzPictureBookParams.getId()) {
                            uploadFile.setRelationId(String.valueOf(zzPictureBookParams.getId()));
                        }
                        uploadFile.setFileExt(fileInfoDTO.getFileSuffix());
                        uploadFile.setSourceModel(fileRelationTypeEnum.getCode());
                        uploadFile.setSize(fileInfoDTO.getSize());
                        uploadFile.setSortNum(uploadFile.getId());
                        zzUploadFileService.save(uploadFile);
                        coverIdList.add(uploadFile.getId());
                    }
                } else {
                    coverIdList.add(fileParams.getId());
                }
            }
        }
        uploadFileParamsList = zzPictureBookParams.getVideoArray();
        if (CollectionUtils.isNotEmpty(uploadFileParamsList)) {
            for (ZzUploadFileParams fileParams : uploadFileParamsList) {
                if (fileParams.getFile() != null) {
                    OssFileResult<FileInfoDTO> fileUploadResult = ossClientService.uploadFile(fileParams.getFile().getBytes(), fileRelationTypeEnum.getOssPath(), fileParams.getFile().getOriginalFilename(), IdUtils.fastSimpleUUID());
                    if (fileUploadResult.isSuccess()) {
                        FileInfoDTO fileInfoDTO = fileUploadResult.getData();
                        ZzUploadFile uploadFile = new ZzUploadFile();
                        uploadFile.setRelationType(fileRelationTypeEnum.getCode());
                        uploadFile.setUrl(fileInfoDTO.getUrl());
                        uploadFile.setOldFileName(fileInfoDTO.getOriginalFilename());
                        uploadFile.setFileName(FileUtils.getName(fileInfoDTO.getNewFileName()));
                        if (null != zzPictureBookParams.getId()) {
                            uploadFile.setRelationId(String.valueOf(zzPictureBookParams.getId()));
                        }
                        uploadFile.setFileExt(fileInfoDTO.getFileSuffix());
                        uploadFile.setSourceModel(fileRelationTypeEnum.getCode());
                        uploadFile.setSize(fileInfoDTO.getSize());
                        uploadFile.setSortNum(uploadFile.getId());
                        zzUploadFileService.save(uploadFile);
                        videoIdList.add(uploadFile.getId());
                    }
                } else {
                    videoIdList.add(fileParams.getId());
                }
            }
        }
        if (!CollectionUtils.isNotEmpty(zzPictureBookParams.getSentence())) {
            zzPictureBookParams.setSentence(Lists.newArrayList());
        }


        if (CollectionUtils.isNotEmpty(zzPictureBookParams.getSentence())) {
            zzPictureBook.setSentence(JSON.toJSONString(zzPictureBookParams.getSentence()));
        }

        if (CollectionUtils.isNotEmpty(coverIdList)) {
            zzPictureBook.setCover(JSON.toJSONString(coverIdList));
        }
        if (CollectionUtils.isNotEmpty(videoIdList)) {
            zzPictureBook.setVideo(JSON.toJSONString(videoIdList));
        }

        if (CollectionUtils.isNotEmpty(zzPictureBookParams.getWords())) {
            zzPictureBook.setWords(JSON.toJSONString(zzPictureBookParams.getWords()));
        }
        if (CollectionUtils.isNotEmpty(zzPictureBookParams.getTag())) {
            zzPictureBook.setTag(JSON.toJSONString(zzPictureBookParams.getTag()));
        }
        //直接是下线状态
        zzPictureBook.setState(CommonEnums.NO.getCode());
        boolean res = this.saveOrUpdate(zzPictureBook);
        if (CollectionUtils.isNotEmpty(CollectionUtils.collate(videoIdList, coverIdList))) {
            //解除关系
            zzUploadFileService.removeRelation(String.valueOf(zzPictureBook.getId()), fileRelationTypeEnum, CollectionUtils.collate(videoIdList, coverIdList));
            //建立关系
            this.zzUploadFileService.updateRelation(String.valueOf(zzPictureBook.getId()), CollectionUtils.collate(videoIdList, coverIdList));
        }
        //自动创建 作业节点
        List<String> nodeNames = JSON.parseArray(sysConfigService.selectConfigByKey("auto_picture_book_days_node"), String.class);
        if (CollectionUtils.isNotEmpty(nodeNames)) {
            Long index = 0L;
            for (String nodeName : nodeNames) {
                if (null == zzPictureNodeService.getOne(Wrappers.lambdaQuery(ZzPictureNode.class)
                        .eq(ZzPictureNode::getNodeType, 3)
                        .eq(ZzPictureNode::getPictureBookId, zzPictureBook.getId())
                        .eq(ZzPictureNode::getNodeName, nodeName)
                        .last(" limit 1 ")
                )) {
                    ZzPictureNode zzPictureNode = new ZzPictureNode();
                    zzPictureNode.setNodeName(nodeName);
                    zzPictureNode.setPictureBookId(zzPictureBook.getId());
                    zzPictureNode.setNodeType(3);
                    zzPictureNode.setSortNo(index++);
                    zzPictureNodeService.save(zzPictureNode);
                }
            }
        }
        return res;
    }

    @Override
    public ZzPictureBookParams selectById(Long id) {
        ZzPictureBookParams zzPictureBookParams = new ZzPictureBookParams();
        ZzPictureBook zzPictureBook = this.getById(id);
        BeanUtils.copyBeanProp(zzPictureBookParams, zzPictureBook);
        zzPictureBookParams.setTag(JSON.parseArray(zzPictureBook.getTag(), String.class));
        zzPictureBookParams.setWords(JSON.parseArray(zzPictureBook.getWords(), String.class));
        if (CollectionUtils.isEmpty(zzPictureBookParams.getWords())) {
            zzPictureBookParams.setWords(Lists.newArrayList());
        }
        if (CollectionUtils.isEmpty(zzPictureBookParams.getTag())) {
            zzPictureBookParams.setTag(Lists.newArrayList());
        }
        if (StringUtils.isNotBlank(zzPictureBook.getSentence())) {
            zzPictureBookParams.setSentence(JSON.parseArray(zzPictureBook.getSentence(), String.class));
        } else {
            zzPictureBookParams.setSentence(Lists.newArrayList(""));
        }
        if (null != zzPictureBook.getUnitId()) {
            ZzCourse zzCourse = this.zzCourseService.getById(zzPictureBook.getUnitId());

            if (null != zzCourse) {
                zzPictureBookParams.setUnitName(zzCourse.getName());
                zzPictureBookParams.setUnitId(zzCourse.getId());
            }
        }
        zzPictureBookParams.setCoverArray(Lists.newArrayList());
        zzPictureBookParams.setVideoArray(Lists.newArrayList());
        if (StringUtils.isNotBlank(zzPictureBook.getCover())) {
            List<Long> fileIdList = JSON.parseArray(zzPictureBook.getCover(), Long.class);
            for (Long fileId : fileIdList) {
                ZzUploadFileParams uploadFileParam = new ZzUploadFileParams();
                ZzUploadFile zzUploadFile = zzUploadFileService.getById(fileId);
                uploadFileParam.setUrl(ossClientService.convertURL(zzUploadFile.getUrl()));
                uploadFileParam.setId(fileId);
                zzPictureBookParams.getCoverArray().add(uploadFileParam);
            }
        }
        if (StringUtils.isNotBlank(zzPictureBook.getVideo())) {
            List<Long> fileIdList = JSON.parseArray(zzPictureBook.getVideo(), Long.class);
            for (Long fileId : fileIdList) {
                ZzUploadFileParams uploadFileParam = new ZzUploadFileParams();
                ZzUploadFile zzUploadFile = zzUploadFileService.getById(fileId);
                uploadFileParam.setUrl(ossClientService.convertURL(zzUploadFile.getUrl()));
                uploadFileParam.setId(fileId);
                zzPictureBookParams.getVideoArray().add(uploadFileParam);
            }
        }
        return zzPictureBookParams;
    }

    @Override
    public List<ZzPictureBook> getZzPictureBookByUnitList(List<Long> unitIdList) {
        return baseMapper.getZzPictureBookByUnitList(unitIdList);
    }

    @Override
    public IPage<QueryZzPictureBookDTO> apiQueryZzPictureBookPage(IPage<QueryZzPictureBookDTO> page, Long stuId, Long schoolId, Long unitId) {
        return baseMapper.apiQueryZzPictureBookPage(page, stuId, schoolId, unitId);
    }

    @Override
    public IPage<ZzPictureBook> apiClassQueryZzPictureBookPage(IPage<ZzPictureBook> page, Long schoolId, Long clzzId, LocalDateTime now) {
        return baseMapper.apiClassQueryZzPictureBookPage(page, schoolId, clzzId, now);
    }

    /**
     * 按照 作业发送逻辑查询绘本列表
     *
     * @param page
     * @param stuId
     * @param schoolId
     * @param unitId
     * @return
     */
    public IPage<ZzPictureBook> apiQueryZzPictureBookPageNews(IPage<QueryZzPictureBookDTO> page, Long stuId, Long schoolId, Long unitId) {
        return baseMapper.apiQueryZzPictureBookPageNews(page, stuId, schoolId, unitId);
    }

    /**
     * 大屏#查询所有绘本列表
     *
     * @param page
     * @param stuId
     * @param schoolId
     * @param unitId
     * @return
     */
    public IPage<ZzPictureBook> apiDeviceZzPictureBookQueryPageNews(IPage<ZzPictureBook> page, String level, Long schoolId, Long unitId,List<Integer> stateList) {
        return baseMapper.apiDeviceZzPictureBookQueryPageNews(page, level, schoolId, unitId,stateList);
    }

    /**
     * 小程序#查询所有绘本列表
     *
     * @param page
     * @param stuId
     * @param schoolId
     * @param unitId
     * @return
     */
    public IPage<ZzPictureBook> apiMiniProZzPictureBookQueryPageNews(IPage<ZzPictureBook> page, String level, Long schoolId, Long unitId,List<Integer> stateList) {
        return baseMapper.apiMiniProZzPictureBookQueryPageNews(page, level, schoolId, unitId,stateList);
    }
}